package com.swx.identityservice.webapis;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.swx.identityservice.dtos.role.InsertRoleInputDto;
import com.swx.identityservice.dtos.role.RoleListOutputDto;
import com.swx.identityservice.dtos.role.RoleOutputDto;
import com.swx.identityservice.dtos.role.UpdateRoleInputDto;
import com.swx.identityservice.models.ScbpDept;
import com.swx.identityservice.models.ScbpRole;
import com.swx.identityservice.service.LoginUser;
import com.swx.identityservice.service.ScbpDeptService;
import com.swx.identityservice.service.ScbpRoleService;
import com.swx.identityservice.service.ScbpUserService;
import com.swx.identityservice.utils.JaxrsResponse;
import com.swx.identityservice.utils.ResponseMessages;
import com.swx.identityservice.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;


/*
 * @controller: 角色 controller
 *
 * */

@Slf4j
@RestController
@Api(tags = "角色控制器")
public class ScbpRoleController {
    @Autowired
    private ScbpRoleService scbpRoleService;
    @Autowired
    private ScbpUserService scbpUserService;
    private ModelMapper modelMapper;
    @Autowired
    private ScbpDeptService scbpDeptService;

    public ScbpRoleController() {
        modelMapper = new ModelMapper();
    }


    @ApiOperation("查询角色分页列表接口+ 根据id查询角色信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageIndex", value = "页码", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize", value = "页容", required = true)
    })

    @GetMapping(value = "/getroles")
    @PreAuthorize("hasAuthority('Roles_Select')")
    public JaxrsResponse get(@RequestParam(defaultValue = "1", value = "pageIndex") int pageIndex,
                             @RequestParam(defaultValue = "10", value = "pageSize") int pageSize,
                             String dealrole,
                             String name,
                             String affiliateddept) {
        PageHelper.startPage(pageIndex, pageSize);
        List<RoleOutputDto> ScbpRoleList = scbpRoleService.selectAllWithOutDeleted(dealrole, name, affiliateddept);
        PageInfo<RoleOutputDto> page = new PageInfo<>(ScbpRoleList);
        RoleListOutputDto userListOutputDto = new RoleListOutputDto();
        userListOutputDto.setTotal(page.getTotal());
        for (int j = 0; j < page.getList().size(); j++) {
            RoleOutputDto userOutputDto = modelMapper.map(page.getList().get(j), RoleOutputDto.class);

            userListOutputDto.addUser(userOutputDto);
        }
        return JaxrsResponse.builder().code(0).status("success").data(userListOutputDto).build();
    }

    @ApiOperation("新增角色")
    @PreAuthorize("hasAuthority('Roles_Insert')")
    @PostMapping(value = "/addrole")
    public JaxrsResponse post(@RequestBody InsertRoleInputDto insertRoleInputDto) {
        ScbpRole scbpRole = modelMapper.map(insertRoleInputDto, ScbpRole.class);
        scbpRole.setCreationtime(new Date());
        Integer topId = getTopId(insertRoleInputDto.getAffiliateddeptid());//单位id
        scbpRole.setAffiliatedunitid(topId);
        scbpRole.setIsdeleted(false);
        LoginUser loginUser = UserUtil.getLoginUser();
        scbpRole.setCreatoruserid(loginUser.getId());

        int sr = scbpRoleService.insert(scbpRole);
        if (sr > 0) return JaxrsResponse.builder().code(0).status("success").build();
        return JaxrsResponse.builder().code(1).status("fail").data(scbpRole).message(ResponseMessages.INSERT_FAIL).build();
    }

    @ApiOperation("编辑角色")
    @PreAuthorize("hasAuthority('Roles_Edit')")
    @PostMapping(value = "/editrole")
    public JaxrsResponse put(@RequestBody UpdateRoleInputDto updateRoleInputDto) {
        ScbpRole scbpRole = modelMapper.map(updateRoleInputDto, ScbpRole.class);

        Integer topId = getTopId(updateRoleInputDto.getAffiliateddeptid());//单位id
        scbpRole.setAffiliatedunitid(topId);
        LoginUser loginUser = UserUtil.getLoginUser();
        scbpRole.setLastmodifieruserid(loginUser.getId());
        scbpRole.setLastmodificationtime(new Date());
        int sr = scbpRoleService.updateByPrimaryKeySelective(scbpRole);
        if (sr > 0) return JaxrsResponse.builder().code(0).status("success").build();
        return JaxrsResponse.builder().code(1).status("fail").message(ResponseMessages.UPDATE_FAIL).build();
    }

    @ApiOperation("删除角色")
    @PreAuthorize("hasAuthority('Roles_Delete')")
    @DeleteMapping(value = "/delrole")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "int", name = "roleId", value = "角色id", required = true)
    })
    public JaxrsResponse delete(@RequestParam int roleId) {

        int count = scbpUserService.selectCountByRoleId(roleId);
        if (count > 0) {
            return JaxrsResponse.builder().code(1).message("请先删除该角色下的人员").build();
        }
        ScbpRole scbpRole = new ScbpRole();
        scbpRole.setId(roleId);
        scbpRole.setIsdeleted(true);
        scbpRole.setDeletiontime(new Date());
        LoginUser loginUser = UserUtil.getLoginUser();
        scbpRole.setDeleteruserid(loginUser.getId());
        int sr = scbpRoleService.updateByPrimaryKeySelective(scbpRole);
        if (sr > 0) {
            return JaxrsResponse.builder().code(0).status("success").data(scbpRole.getId()).build();
        }
        return JaxrsResponse.builder().code(1).status("fail").message(ResponseMessages.DELETE_FAIL).build();
    }

    //递归查询
    public String getTopName(Integer id) {
        String topDept = "";
        ScbpDept scbpDept = scbpDeptService.selectDeptById(id);
        if (scbpDept.getPid() != 0) {//这就是出口
            return getTopName(scbpDept.getPid());
        } else {
            topDept = scbpDept.getTitle();
            return topDept;
        }
    }

    /**
     * 递归查询顶级节点id
     *
     * @param id
     * @return
     */
    public Integer getTopId(Integer id) {
        Integer topid = 0;
        ScbpDept scbpDept = scbpDeptService.selectDeptById(id);
        if (scbpDept.getPid() != 0) {//这就是出口
            return getTopId(scbpDept.getPid());
        } else {
            topid = scbpDept.getId();
            return topid;
        }
    }
}
